package com.itools.core.ucenter.service.impl;


import com.itools.core.ucenter.em.LoginTypeEnum;
import com.itools.core.ucenter.em.UcenterCodeBean;
import com.itools.core.exception.AppException;
import com.itools.core.ucenter.mapper.PermissionMapper;
import com.itools.core.ucenter.mapper.IUserInfoMapper;
import com.itools.core.ucenter.pojo.SysPermission;
import com.itools.core.ucenter.pojo.SysUser;
import com.itools.core.ucenter.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @project: itools-backend
 * @description:
 * @author: XUCHANG
 * @create: 2021-03-29 14:00
 */
@Service("userDetailsService")
@Log4j2
public class UserServiceImpl implements UserService {

    @Autowired
    private IUserInfoMapper IUserInfoMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser getByUsername(String username) {
        return IUserInfoMapper.getByUsername(username);
    }

    /**
     * 验证密码模式的用户账号、应用
     * @param parameters
     * @return
     */
    @Override
    public boolean verifyUserByPasswordType(Map<String, String> parameters) {

        if (!parameters.containsKey("grant_type") || !parameters.get("grant_type").equals(LoginTypeEnum.PASSWORD.getName())){
            return false;
        }
        if (!parameters.containsKey("username") || !parameters.containsKey("password")){
            log.error("账号密码未输入");
            throw new AppException(UcenterCodeBean.UcenterCode.FAIL_USERNAME_PASSWORD.code);
        }
        String username = parameters.get("username");
        String password = parameters.get("password");

        SysUser sysUser = getByUsername(username);
        if (sysUser == null){
            log.error("账号不存在或账号密码错误");
            throw new AppException(UcenterCodeBean.UcenterCode.USERNAME_NOT_FOUND_EXCEPTION.code);
        }

        if(!passwordEncoder.matches(password,sysUser.getPassword())){
            log.error("账号不存在或账号密码错误");
            throw new AppException(UcenterCodeBean.UcenterCode.USERNAME_NOT_FOUND_EXCEPTION.code);
        }

        return true;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = getByUsername(username);
        if (user==null){
            log.error("账号不存在或账号密码错误");
            throw new UsernameNotFoundException("账号不存在或账号密码错误");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysPermission> permissions = permissionMapper.selectByUserId(user.getId());

        permissions.forEach(permission -> {
            if (permission!=null && !StringUtils.isEmpty(permission.getEnname())){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getEnname());
                authorities.add(grantedAuthority);
            }
        });
        return new User(user.getUsername(),user.getPassword(),authorities);
    }

}
